package com.its.common.gateway.filter;

import com.its.common.gateway.config.IgnoreWhiteProperties;
import com.its.common.gateway.config.UnIgnoreBlackProperties;
import com.its.common.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 黑名单过滤器
 *
 * @author xiaxp
 */
@EnableConfigurationProperties({UnIgnoreBlackProperties.class, IgnoreWhiteProperties.class})
public class BlackListUrlFilter implements GlobalFilter, Ordered {
    /**
     * 过滤的 uri 黑名单见地址，可在nacos中添加
     */
    @Autowired
    private UnIgnoreBlackProperties blackProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        if (blackProperties.matchBlacklist(url)) {
            return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "请求地址不允许访问");
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100000;
    }

}
